* This creates the output for Table 1, Table 2, Appendix Table A1, Figure A1 and Figure A2

clear all

use "$savedata/masterdata.dta", replace

keep if sample25==1
gen vol = vol25

* Generate Table 1 output here - patient summary statistics
su derv_age male white stemi2 arthero arythmia arrest shock charlindex prevyear_stroke prevyear_cost prevyear_admit_em prevyear_los all_death30 all_death365

preserve
* Generate Table 2 - doctor summary statistics

* Marker for number of hospitals they work in
bys pconsult trust_code: gen hosp=1 if _n==1

* Marker for number of years they appear in the data
bys pconsult finyear: gen year=1 if _n==1

* Calculate annual volumes
egen yvol = sum(ami), by(pconsult finyear)
egen ystemi = sum(stemi2), by(pconsult finyear)

collapse (sum) ami stemi2 hosp year (mean) all_death30 all_death365 yvol, by(pconsult)

gen multi = 0
replace multi = 1 if hosp>1

* Table 2 output here - descriptive statistics of cardiologists 
su ami stemi2 yvol all_death* multi hosp year

restore


* Create Appendix Table 1 - sum stats separately for linkers and non-linkers

preserve
* Marker for number of hospitals they work in
bys pconsult trust_code: gen hosp=1 if _n==1
egen temp2 = sum(hosp), by(pconsult)

gen mover = 0
replace mover = 1 if temp2>1


* Marker for number of years they appear in the data
bys pconsult finyear: gen year=1 if _n==1

* Calculate annual volumes
egen yvol = sum(ami), by(pconsult finyear)
egen ystemi = sum(stemi2), by(pconsult finyear)

collapse (sum) ami stemi2 hosp year (mean) all_death30 all_death365 yvol ystemi (max) mover, by(pconsult)

gen multi = 0
replace multi = 1 if hosp>1

gen nstemi = ami - stemi2
gen ynstemi = yvol - ystemi

su ami stemi2 yvol all_death* multi hosp year

* Appendix Table A1 - output here (also gives number of movers)
bys mover: su ami stemi2 yvol all_death* multi hosp year

restore

* Make connected set graphs

collapse (sum) ami, by(pconsult trust_code)

bys pconsult: gen z=_n

gen zz = 0
replace zz = 1 if z>1

egen multiple_z = max(zz), by(pconsult)

* Count number of consultants
unique pconsult

* Count number of consultants working in multiple hospitals ('transferrers')
unique pconsult if multiple_z==1


* Number of linking consultants across hospitals - Figure A1
preserve
keep if multiple_z==1
gen one=1
collapse (sum) one, by(trust_code)
histogram one, freq width(1) ysc(r(0(5)25)) ylabel(0(5)25) ytitle(Number of hospitals) xtitle(Number of linking consultants) scheme(s1mono) start(1)
graph export "$results/figA1.pdf", as(pdf) replace
restore

* Number of patients treated by linking consultants in secondary hospitals - Figure A2
preserve
keep if multiple_z==1
collapse (min) ami, by(pconsult)
histogram ami, freq xtitle(Min number of AMI patients treated by cardiologist) ytitle(Number of cardiologists) scheme(s1mono) width(10)
graph export "$results/figA2.pdf", as(pdf) replace
restore
